import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '../store'
import router from '../router'
import { browserName, browserVersion,  clientType,
		deviceId, requestId, timestamp } from '../utils/util'



//全局默认配置
axios.defaults.timeout = 10000;
//axios.defaults.baseURL = 'http://192.168.10.174:8443';
axios.defaults.baseURL = process.env.BASE_URL;
axios.defaults.withCredentials = true;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';



//请求拦截器
axios.interceptors.request.use(config => {

	// 根据方法进行数据转换
	if ((config.method=="get" || config.method=="delete") && !config.params) {
		config.params = config.data;
		config.paramsSerializer = function(params) {
			return qs.stringify(params, { arrayFormat: 'repeat' })
		}
	} else {
		config.data = qs.stringify(config.data, { arrayFormat: 'repeat' });
	}
	//设置请求头
	config.headers['x-auth-token'] = store.getters.token;
	config.headers['x-auth-scope'] = store.getters.scope;
	config.headers['x-app-version'] = store.getters.version;
	config.headers['x-app-channel'] = store.getters.channel;
	config.headers['x-bundle-id'] = store.getters.bundleId;
	config.headers['x-client-type'] = clientType();
	config.headers['x-client-name'] = browserName();
	config.headers['x-client-version'] = browserVersion();
	config.headers['x-client-device-id'] = deviceId();
	config.headers['x-request-id'] = requestId();
	config.headers['x-timestamp'] = timestamp();

	return config;
}, error => {
	Message.closeAll(); //先关闭其他异常提示
	Message({ message: error, type: 'error' });
	return Promise.reject(error);
})

//响应拦截器
axios.interceptors.response.use(response => {
	//检查是否登录
	if (!response.data.code) {
		checkIsLogin(response.data.code);
	}
	return response;
}, error => {
    console.log(error.response)
	Message.closeAll(); //先关闭其他异常提示
    if(error.code == 'ECONNABORTED' && error.message.indexOf('timeout')!=-1){
		Message({ message: '请求超时，请检查网络连接', type: 'error' });
	} else if (error.response) {
		//检查是否登录
		const { status, data } = error.response;
		checkIsLogin(status);
		//判断服务器返回异常
		parseStatusError(status, data);
	} else {
		if (error.message == 'Network Error') {
			Message({ message: '服务网关异常，请稍后重试', type: 'error' });
		} else {
			Message({ message: error.message, type: 'error' });
		}
	}
	return Promise.reject(error);
})

/**
 * 检查用户是否登录
 */
const checkIsLogin = (status) => {
	//未登录状态时的逻辑
	if (status==401) {
		store.dispatch("logout");
		router.replace({path:'/login', query: {rt: window.location.pathname + window.location.search}});
	}
}

/**
 * 检查返回异常码
 */
const parseStatusError = (status, data) => {
	//未登录状态时的逻辑
	let message = '';
	switch (status) {
		case 503, 504:
			message = '服务访问不可用，请稍后重试';
			break;
		case 429:
			message = '操作过于频繁，请稍后重试';
			break;
		default:
			message = data.msg? data.msg: data.error +": "+ data.message;
			break;
	}
	Message({ message: message, type: 'error' });
}

export default {
	//axios本身就是基于Promise的http库
	fetch (api, params) {
		//const { tag } = api;
		if(!api) {
			Message.closeAll(); //先关闭其他异常提示
			Message({ message: "fetch api url not found", type: 'error' });
			return Promise.reject("fetch api url not found");
		}
	  	return axios({
			method: api.method ? api.method: "get",
			url: api.url,
			data: params
		}).then(res => {
			return res.data;
		});
	},
	all(iterable) {
		return axios.all(iterable);
	},
	spread(callback) {
		return axios.spread(callback);
	}
}
